# MonitorPlatform 项目结构自动化构建脚本
Write-Host "开始构建 MonitorPlatform 项目结构..." -ForegroundColor Green

# 确保在正确的目录
$projectRoot = Split-Path -Parent $MyInvocation.MyCommand.Path
Set-Location $projectRoot

# 创建src目录下的所有项目
Write-Host "创建核心项目..." -ForegroundColor Yellow

# 数据访问层
Set-Location src
dotnet new classlib -n MonitorPlatform.Data --force
dotnet new webapi -n MonitorPlatform.API --force
dotnet new worker -n MonitorPlatform.Processor --force
dotnet new classlib -n MonitorPlatform.Common --force
dotnet new mstest -n MonitorPlatform.Tests --force

# 返回根目录并添加项目到解决方案
Set-Location ..
dotnet sln add src/MonitorPlatform.Gateway/MonitorPlatform.Gateway.csproj
dotnet sln add src/MonitorPlatform.Core/MonitorPlatform.Core.csproj
dotnet sln add src/MonitorPlatform.Data/MonitorPlatform.Data.csproj
dotnet sln add src/MonitorPlatform.API/MonitorPlatform.API.csproj
dotnet sln add src/MonitorPlatform.Processor/MonitorPlatform.Processor.csproj
dotnet sln add src/MonitorPlatform.Common/MonitorPlatform.Common.csproj
dotnet sln add src/MonitorPlatform.Tests/MonitorPlatform.Tests.csproj

Write-Host "添加项目引用..." -ForegroundColor Yellow

# 设置项目依赖关系
Set-Location src

# Gateway 依赖 Core 和 Common
Set-Location MonitorPlatform.Gateway
dotnet add reference ../MonitorPlatform.Core/MonitorPlatform.Core.csproj
dotnet add reference ../MonitorPlatform.Common/MonitorPlatform.Common.csproj

# API 依赖 Core, Data 和 Common
Set-Location ../MonitorPlatform.API
dotnet add reference ../MonitorPlatform.Core/MonitorPlatform.Core.csproj
dotnet add reference ../MonitorPlatform.Data/MonitorPlatform.Data.csproj
dotnet add reference ../MonitorPlatform.Common/MonitorPlatform.Common.csproj

# Processor 依赖 Core, Data 和 Common
Set-Location ../MonitorPlatform.Processor
dotnet add reference ../MonitorPlatform.Core/MonitorPlatform.Core.csproj
dotnet add reference ../MonitorPlatform.Data/MonitorPlatform.Data.csproj
dotnet add reference ../MonitorPlatform.Common/MonitorPlatform.Common.csproj

# Core 依赖 Common
Set-Location ../MonitorPlatform.Core
dotnet add reference ../MonitorPlatform.Common/MonitorPlatform.Common.csproj

# Data 依赖 Common
Set-Location ../MonitorPlatform.Data
dotnet add reference ../MonitorPlatform.Common/MonitorPlatform.Common.csproj

# Tests 依赖所有项目
Set-Location ../MonitorPlatform.Tests
dotnet add reference ../MonitorPlatform.Gateway/MonitorPlatform.Gateway.csproj
dotnet add reference ../MonitorPlatform.Core/MonitorPlatform.Core.csproj
dotnet add reference ../MonitorPlatform.Data/MonitorPlatform.Data.csproj
dotnet add reference ../MonitorPlatform.API/MonitorPlatform.API.csproj
dotnet add reference ../MonitorPlatform.Processor/MonitorPlatform.Processor.csproj
dotnet add reference ../MonitorPlatform.Common/MonitorPlatform.Common.csproj

Set-Location ../..

Write-Host "创建项目目录结构..." -ForegroundColor Yellow

# 为每个项目创建标准目录结构
$projects = @(
    "MonitorPlatform.Gateway",
    "MonitorPlatform.Core", 
    "MonitorPlatform.Data",
    "MonitorPlatform.API",
    "MonitorPlatform.Processor",
    "MonitorPlatform.Common"
)

foreach ($project in $projects) {
    $projectPath = "src/$project"
    
    # Gateway特定目录
    if ($project -eq "MonitorPlatform.Gateway") {
        New-Item -ItemType Directory -Force -Path "$projectPath/Controllers"
        New-Item -ItemType Directory -Force -Path "$projectPath/Middleware"
        New-Item -ItemType Directory -Force -Path "$projectPath/Filters"
        New-Item -ItemType Directory -Force -Path "$projectPath/Hubs"
        New-Item -ItemType Directory -Force -Path "$projectPath/Services"
    }
    
    # Core业务逻辑目录
    if ($project -eq "MonitorPlatform.Core") {
        New-Item -ItemType Directory -Force -Path "$projectPath/Models"
        New-Item -ItemType Directory -Force -Path "$projectPath/Services"
        New-Item -ItemType Directory -Force -Path "$projectPath/Interfaces"
        New-Item -ItemType Directory -Force -Path "$projectPath/Validators"
        New-Item -ItemType Directory -Force -Path "$projectPath/Enums"
        New-Item -ItemType Directory -Force -Path "$projectPath/DTOs"
    }
    
    # Data访问层目录
    if ($project -eq "MonitorPlatform.Data") {
        New-Item -ItemType Directory -Force -Path "$projectPath/Entities"
        New-Item -ItemType Directory -Force -Path "$projectPath/Repositories"
        New-Item -ItemType Directory -Force -Path "$projectPath/Context"
        New-Item -ItemType Directory -Force -Path "$projectPath/Configurations"
        New-Item -ItemType Directory -Force -Path "$projectPath/Migrations"
    }
    
    # API服务目录
    if ($project -eq "MonitorPlatform.API") {
        New-Item -ItemType Directory -Force -Path "$projectPath/Controllers"
        New-Item -ItemType Directory -Force -Path "$projectPath/Filters"
        New-Item -ItemType Directory -Force -Path "$projectPath/Middleware"
        New-Item -ItemType Directory -Force -Path "$projectPath/Services"
    }
    
    # Processor流处理目录
    if ($project -eq "MonitorPlatform.Processor") {
        New-Item -ItemType Directory -Force -Path "$projectPath/Workers"
        New-Item -ItemType Directory -Force -Path "$projectPath/Processors"
        New-Item -ItemType Directory -Force -Path "$projectPath/Handlers"
        New-Item -ItemType Directory -Force -Path "$projectPath/Services"
    }
    
    # Common公共组件目录
    if ($project -eq "MonitorPlatform.Common") {
        New-Item -ItemType Directory -Force -Path "$projectPath/Extensions"
        New-Item -ItemType Directory -Force -Path "$projectPath/Helpers"
        New-Item -ItemType Directory -Force -Path "$projectPath/Constants"
        New-Item -ItemType Directory -Force -Path "$projectPath/Utilities"
        New-Item -ItemType Directory -Force -Path "$projectPath/Exceptions"
    }
}

Write-Host "创建配置文件..." -ForegroundColor Yellow

# 创建docker-compose.yml
@"
version: '3.8'
services:
  gateway:
    build:
      context: .
      dockerfile: src/MonitorPlatform.Gateway/Dockerfile
    ports:
      - "8080:80"
    environment:
      - ASPNETCORE_ENVIRONMENT=Development
    depends_on:
      - postgres
      - redis
      - elasticsearch

  api:
    build:
      context: .
      dockerfile: src/MonitorPlatform.API/Dockerfile
    ports:
      - "8081:80"
    environment:
      - ASPNETCORE_ENVIRONMENT=Development
    depends_on:
      - postgres
      - redis

  processor:
    build:
      context: .
      dockerfile: src/MonitorPlatform.Processor/Dockerfile
    environment:
      - ASPNETCORE_ENVIRONMENT=Development
    depends_on:
      - postgres
      - redis
      - kafka

  postgres:
    image: postgres:13
    environment:
      POSTGRES_DB: monitor_platform
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: postgres
    ports:
      - "5432:5432"
    volumes:
      - postgres_data:/var/lib/postgresql/data

  redis:
    image: redis:6-alpine
    ports:
      - "6379:6379"

  elasticsearch:
    image: elasticsearch:7.14.0
    environment:
      - discovery.type=single-node
      - "ES_JAVA_OPTS=-Xms512m -Xmx512m"
    ports:
      - "9200:9200"
    volumes:
      - elasticsearch_data:/usr/share/elasticsearch/data

  kibana:
    image: kibana:7.14.0
    ports:
      - "5601:5601"
    environment:
      ELASTICSEARCH_HOSTS: http://elasticsearch:9200
    depends_on:
      - elasticsearch

  kafka:
    image: confluentinc/cp-kafka:latest
    environment:
      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
    ports:
      - "9092:9092"
    depends_on:
      - zookeeper

  zookeeper:
    image: confluentinc/cp-zookeeper:latest
    environment:
      ZOOKEEPER_CLIENT_PORT: 2181
      ZOOKEEPER_TICK_TIME: 2000
    ports:
      - "2181:2181"

volumes:
  postgres_data:
  elasticsearch_data:
"@ | Out-File -FilePath "docker/docker-compose.yml" -Encoding UTF8

# 创建数据库初始化脚本
@"
-- Monitor Platform Database Schema
CREATE SCHEMA IF NOT EXISTS monitor;

-- Performance Metrics Table
CREATE TABLE monitor.performance_metrics (
    id BIGSERIAL PRIMARY KEY,
    app_id VARCHAR(50) NOT NULL,
    session_id VARCHAR(100) NOT NULL,
    page_url TEXT NOT NULL,
    metric_type VARCHAR(50) NOT NULL,
    metric_value DECIMAL(10,3) NOT NULL,
    timestamp TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    user_agent TEXT,
    ip_address INET,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);

-- Error Logs Table
CREATE TABLE monitor.error_logs (
    id BIGSERIAL PRIMARY KEY,
    app_id VARCHAR(50) NOT NULL,
    session_id VARCHAR(100) NOT NULL,
    error_type VARCHAR(100) NOT NULL,
    error_message TEXT NOT NULL,
    stack_trace TEXT,
    page_url TEXT NOT NULL,
    timestamp TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    user_agent TEXT,
    ip_address INET,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);

-- Network Requests Table
CREATE TABLE monitor.network_requests (
    id BIGSERIAL PRIMARY KEY,
    app_id VARCHAR(50) NOT NULL,
    session_id VARCHAR(100) NOT NULL,
    request_url TEXT NOT NULL,
    method VARCHAR(10) NOT NULL,
    status_code INTEGER,
    response_time INTEGER,
    timestamp TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);

-- User Behaviors Table
CREATE TABLE monitor.user_behaviors (
    id BIGSERIAL PRIMARY KEY,
    app_id VARCHAR(50) NOT NULL,
    session_id VARCHAR(100) NOT NULL,
    action_type VARCHAR(50) NOT NULL,
    element_selector TEXT,
    page_url TEXT NOT NULL,
    timestamp TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    additional_data JSONB,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);

-- Create indexes for better performance
CREATE INDEX idx_performance_metrics_app_timestamp ON monitor.performance_metrics(app_id, timestamp);
CREATE INDEX idx_error_logs_app_timestamp ON monitor.error_logs(app_id, timestamp);
CREATE INDEX idx_network_requests_app_timestamp ON monitor.network_requests(app_id, timestamp);
CREATE INDEX idx_user_behaviors_app_timestamp ON monitor.user_behaviors(app_id, timestamp);

-- Create partitions for time-based data (optional)
-- This would be implemented for production environments with large data volumes
"@ | Out-File -FilePath "scripts/sql/init.sql" -Encoding UTF8

# 创建setup脚本
@"
#!/bin/bash
# MonitorPlatform Setup Script

echo "Setting up MonitorPlatform..."

# Build all projects
dotnet build

# Restore packages
dotnet restore

# Setup database (requires Docker)
docker-compose -f docker/docker-compose.yml up -d postgres

# Wait for database to be ready
sleep 10

# Run migrations (if any)
# dotnet ef database update --project src/MonitorPlatform.Data

echo "Setup completed!"
echo "Run 'docker-compose -f docker/docker-compose.yml up' to start all services"
"@ | Out-File -FilePath "scripts/setup/setup.sh" -Encoding UTF8

# 创建Windows setup脚本
@"
@echo off
echo Setting up MonitorPlatform...

REM Build all projects
dotnet build

REM Restore packages
dotnet restore

REM Setup database (requires Docker)
docker-compose -f docker/docker-compose.yml up -d postgres

REM Wait for database to be ready
timeout /t 10

REM Run migrations (if any)
REM dotnet ef database update --project src/MonitorPlatform.Data

echo Setup completed!
echo Run 'docker-compose -f docker/docker-compose.yml up' to start all services
pause
"@ | Out-File -FilePath "scripts/setup/setup.bat" -Encoding UTF8

# 创建项目文档
@"
# MonitorPlatform - 企业级性能监控平台

## 项目概述
MonitorPlatform 是一个现代化的企业级性能监控平台，专为处理大规模前端应用监控数据而设计。

## 架构设计

### 系统架构
```
┌────────────────────────┬────────────────────────────────────┐
│                    数据接收网关                                │
│  - 负载均衡  - 数据验证  - 限流熔断  - 数据分流              │
└────────────────────────┬────────────────────────────────────┘
                         │ HTTPS/gRPC
┌────────────────────────▼────────────────────────────────────┐
│                  数据处理管道                                  │
├─────────────┬─────────────┬─────────────┬─────────────────────┤
│ 实时流处理   │  数据清洗   │  数据聚合   │    异常检测        │
│  (Kafka)    │  (Flink)    │ (ClickHouse)│   (规则引擎)       │
└─────────────┴─────────────┴─────────────┴─────────────────────┘
                         │
┌────────────────────────▼────────────────────────────────────┐
│                   存储层                                      │
├─────────────┬─────────────┬─────────────┬─────────────────────┤
│  时序数据库  │  日志存储   │  元数据库   │    对象存储        │
│(InfluxDB)   │(Elasticsearch)│(PostgreSQL)│     (S3)          │
└─────────────┴─────────────┴─────────────┴─────────────────────┘
                         │
┌────────────────────────▼────────────────────────────────────┐
│                应用服务层                                      │
├─────────────┬─────────────┬─────────────┬─────────────────────┤
│  API 服务   │  查询服务   │  告警服务   │   分析服务         │
└─────────────┴─────────────┴─────────────┴─────────────────────┘
                         │
┌────────────────────────▼────────────────────────────────────┐
│                 前端展示层                                     │
├─────────────┬─────────────┬─────────────┬─────────────────────┤
│  监控大屏   │  错误分析   │  性能分析   │   告警管理         │
└─────────────┴─────────────┴─────────────┴─────────────────────┘
```

## 项目结构

### 核心模块
- **MonitorPlatform.Gateway**: 数据接收网关，负责接收前端监控数据
- **MonitorPlatform.Core**: 核心业务逻辑，包含领域模型和业务规则  
- **MonitorPlatform.Data**: 数据访问层，支持多种存储引擎
- **MonitorPlatform.API**: 查询API服务，提供数据查询接口
- **MonitorPlatform.Processor**: 流处理服务，实时处理监控数据
- **MonitorPlatform.Common**: 公共组件，包含工具类和扩展方法

### 技术栈
- **.NET 8**: 现代化的后端框架
- **PostgreSQL**: 主数据库
- **Redis**: 缓存和会话存储
- **Elasticsearch**: 日志搜索和分析
- **Kafka**: 消息队列和流处理
- **Docker**: 容器化部署

## 快速开始

### 环境要求
- .NET 8 SDK
- Docker & Docker Compose
- PostgreSQL 13+

### 安装步骤
1. 克隆项目: `git clone <repository>`
2. 运行安装脚本: `./scripts/setup/setup.sh` (Linux) 或 `scripts/setup/setup.bat` (Windows)
3. 启动服务: `docker-compose -f docker/docker-compose.yml up`

### 开发调试
```bash
# 构建项目
dotnet build

# 运行Gateway
dotnet run --project src/MonitorPlatform.Gateway

# 运行API服务
dotnet run --project src/MonitorPlatform.API

# 运行流处理服务
dotnet run --project src/MonitorPlatform.Processor
```

## API文档
- Gateway API: http://localhost:8080/swagger
- Query API: http://localhost:8081/swagger

## 监控面板
- Kibana: http://localhost:5601

## 性能特性
- 支持每秒10万+监控事件处理
- 毫秒级实时告警
- 支持水平扩展
- 99.9%+ 可用性保障

## 贡献指南
详见 [CONTRIBUTING.md](CONTRIBUTING.md)

## 许可证
MIT License
"@ | Out-File -FilePath "docs/README.md" -Encoding UTF8

Write-Host "项目结构构建完成!" -ForegroundColor Green
Write-Host "项目位置: $projectRoot" -ForegroundColor Cyan
Write-Host "下一步:" -ForegroundColor Yellow
Write-Host "1. 运行 'dotnet build' 构建项目" -ForegroundColor White
Write-Host "2. 运行 'docker-compose -f docker/docker-compose.yml up' 启动服务" -ForegroundColor White
Write-Host "3. 访问 http://localhost:8080/swagger 查看API文档" -ForegroundColor White 